package edu.uit.se.laps.web.controller;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import edu.uit.se.laps.web.model.CTDonHang;
import edu.uit.se.laps.web.model.SanPham;
import edu.uit.se.laps.web.util.HibernateUtil;

public class CTDonHangManager extends HibernateUtil {
	
	public CTDonHang addCTDonHang(CTDonHang cTDH){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(cTDH);
		session.getTransaction().commit();
		return cTDH;
	}
	
	public CTDonHang addCTDonHang(SanPham sp, int soLuong){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Integer ID = null;
		
		int iddh = 0;
		int idsp = sp.getIdSP();
		float gia = sp.getGia();
		float thanhtien = gia * soLuong;
		
		CTDonHang cTDH = new CTDonHang();//iddh, idsp, gia, soLuong, thanhtien);
//		cTDH.setIdCTDH(1);
//		cTDH.setIdDH(0);
//		cTDH.setIdSP(sp.getIdSP());
//		cTDH.setDonGia(sp.getGia());
//		cTDH.setSoLuong(soLuong);
//		float thanhtien = soLuong * cTDH.getDonGia();
//		cTDH.setThanhTien(thanhtien);
		
		session.save(cTDH);
		
		session.getTransaction().commit();
		return cTDH;
	}
	
	
	public CTDonHang deleteCTDonHang(int id){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		CTDonHang cTDH = (CTDonHang) session.load(CTDonHang.class, id);
		if (null != cTDH){
			session.delete(cTDH);
		}
		session.getTransaction().commit();
		return cTDH;
	}
	
	public List<CTDonHang> list() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<CTDonHang> cTDHs = null;
		try {
			cTDHs = (List<CTDonHang>) session.createQuery("from CTDonHang").list();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return cTDHs;
	}
	
	public boolean updateCTDH(CTDonHang cTDH){
		boolean result = false;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try {
			session.update(cTDH);
			result = true;
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return result;
	}
}
